<?php

namespace App\Http\Middleware;

use Closure;

class AesMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 解密请求参数
        foreach ($request->all() as $key => $value) {
            $decrypted = openssl_decrypt($value, 'AES-256-CBC', env('AES_KEY'), 0, env('AES_IV'));
            $request->merge([$key => $decrypted]);
        }

        // 处理请求
        $response = $next($request);

        // 加密响应参数
        $content = $response->getContent();
        if ($content==''){
            $response->setContent('');
            return $response;
        }
        $encrypted = openssl_encrypt($content, 'AES-256-CBC', env('AES_KEY'), 0, env('AES_IV'));
        $response->setContent($encrypted);

        return $response;
    }
}
